<?php

namespace app\controller\admin\yys;

use app\model\api\YysHero;
use app\model\api\YysSkill;
use laytp\controller\Backend;
use laytp\library\CommonFun;
use think\facade\Db;

/**
 * Class Skill
 * @package app\controller\admin\yys
 */
class Skill extends Backend
{
    /**
     * api_log模型对象
     * @var \app\model\api\Log
     */
    protected $model;
    protected $hasSoftDel=0;//是否拥有软删除功能

    protected $noNeedLogin = []; // 无需登录即可请求的方法
    protected $noNeedAuth = ['index', 'info']; // 无需鉴权即可请求的方法

    public $orderRule = ['id' => 'desc'];

    public function _initialize()
    {
        $this->model = new YysSkill();
    }


    //添加
    public function add()
    {
        $post     = CommonFun::filterPostData($this->request->post());
        if(empty($post['role_id'])){
            throw new \Exception('请选择角色');
        }
        $insData['category'] = $post['category'];
        $insData['role_id']  = $post['role_id'];
        $insData['name']     = $post['name'];
        $insData['ico']      = $post['ico'];
        $insData['cost']     = $post['cost'];
        $insData['type']     = $post['type'];
        $insData['effect']   = $post['effect'];
        $insData['grade']    = json_encode(array_filter(explode(',',$post['grade'])),JSON_UNESCAPED_UNICODE);
        $insData['create_time'] = time();

        try {
            $save = $this->model->save($insData);
            if (!$save) throw new \Exception('保存失败');
            $this->clearCache();
            return $this->success('保存成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit()
    {
        $id = $this->request->param('id');
        $post = CommonFun::filterPostData($this->request->post());
        if(empty($post['role_id'])){
            throw new \Exception('请选择角色');
        }

        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');

        $row->category    = $post['category'];
        $row->role_id     = $post['role_id'];
        $row->name        = $post['name'];
        $row->ico         = $post['ico'];
        $row->cost        = $post['cost'];
        $row->type        = $post['type'];
        $row->effect      = $post['effect'];
        $row->grade = json_encode(array_filter(explode(',',$post['grade'])),JSON_UNESCAPED_UNICODE);
        try {
            $save = $row->save();
            if ($save === false) throw new \Exception('保存失败');
            $this->clearCache();
            return $this->success('保存成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    public function info(){
        $id = $this->request->param('id');

        $role = $this->model->where('id',$id)->find()->toArray();
        $role['grade']   = json_decode($role['grade'],true);

        return $this->success('获取成功', $role);
    }

}